package com.kuang.config;

import org.springframework.security.config.annotation.authentication.builders.AuthenticationManagerBuilder;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;

/**
 *  Security配置文件
 */
@EnableWebSecurity
public class SecurityConfig extends WebSecurityConfigurerAdapter {


    //授权
    @Override
    protected void configure(HttpSecurity http) throws Exception {
        //定制首页可以随意访问
        http.authorizeRequests().antMatchers("/","/index").permitAll();

        //level1页面：vip1 2 3 都可以访问该页面
        http.authorizeRequests().antMatchers("/level1/**").hasRole("vip1");

        //level2页面：vip2 3可以访问
        http.authorizeRequests().antMatchers("/level2/**").hasRole("vip2");

        //level3页面：vip3才能访问
        http.authorizeRequests().antMatchers("/level3/**").hasRole("vip3");

        //开启自动配置的登录页面
        // /login 请求来到登录页
        // /login?error 重定向到这里表示登录失败
        // loginPage：使用自己的登录叶页面
        // usernameParameter 使用自定义页面登录页面的时候form表单 用户名对应input框的name值
        // passwordParameter .................................密码对应input框的name值
        http.formLogin().usernameParameter("name").passwordParameter("pwd").loginPage("/toLogin").loginProcessingUrl("/login");

        //如果登出失败    设置这个 防止网站攻击
        http.csrf().disable();

        //登出    登出成功后跳转到index.html
        http.logout().logoutSuccessUrl("/");

        //记住我
        //rememberMeParameter 记住我的参数
        http.rememberMe().rememberMeParameter("remember");
    }

    //认证
    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication().passwordEncoder(new BCryptPasswordEncoder())
                .withUser("kuangshen").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2")
                .and()
                .withUser("admin").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1","vip2","vip3")
                .and()
                .withUser("guest").password(new BCryptPasswordEncoder().encode("123456")).roles("vip1");

    }
}
